package com.wiz.weixin.service.impl;

import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.annotation.Resource;

import org.springframework.stereotype.Service;

import com.google.gson.Gson;
import com.google.gson.GsonBuilder;
import com.google.gson.reflect.TypeToken;
import com.wiz.weixin.TO.StationTO;
import com.wiz.weixin.TO.VerificationCodeTO;
import com.wiz.weixin.common.Constant;
import com.wiz.weixin.manager.HttpManager;
import com.wiz.weixin.mapper.StationMapper;
import com.wiz.weixin.mapper.VerificationCodeMapper;
import com.wiz.weixin.service.VerificationCodeService;
/**
 * 校验码
 * @author xxy
 *
 */
@Service("verificationCodeService")
public class VerificationCodeServiceImpl implements VerificationCodeService {
	private Gson gson = new GsonBuilder().disableHtmlEscaping().create();
	@Resource
	private VerificationCodeMapper verificationCodeMapper;
	@Resource
	private HttpManager httpManager;
	@Resource
	private StationMapper stationMapper;
	/***
	 * 发送
	 */
	@Override
	public int sendCode( String phoneNum,String stationId) throws Exception {
		int count = 0;
		int vcode= 0;
		VerificationCodeTO verificationCodeTO = null;
		List<VerificationCodeTO>list = verificationCodeMapper.getCode(phoneNum, null);
		if(list == null || list.size() == 0){
			vcode=(int)(Math.random()*999999);
			verificationCodeTO = new VerificationCodeTO(0, vcode, phoneNum,
					1, 1, new Date(), new Date(), 1);
			verificationCodeMapper.save(verificationCodeTO);
		}else{
			verificationCodeTO = list.get(0);
			vcode = verificationCodeTO.getCode();
			count = verificationCodeTO.getSentCnt();
			if(count>=5){
				throw new Exception("当天获得验证码已超过上限，请明天后再来注册！");
			}
			verificationCodeTO.setSentCnt(verificationCodeTO.getSentCnt()+1);
			verificationCodeMapper.update(verificationCodeTO);
		}
		
		
		List<StationTO>stations = stationMapper.getStation(stationId);
		if(list == null || list.size()<0){
			throw new Exception("没有找到当前站点");
		}
		StationTO stationTO = stations.get(0);
		Map<String,String> params = new HashMap<String,String>();
		
		params.put("HQId", stationTO.getHqId());
		params.put("stationId", stationTO.getStationId());
		params.put("phoneNum", phoneNum);
		params.put("msg", "你注册"+stationTO.getHqName()+"的验证码是"+vcode);
		params.put("type", "6");
		
		String response = httpManager.getHttpsResponseByPost(Constant.SEND_CODE_URL, params, "utf-8");
		System.out.println(response);
    	Map<String,String> map = gson.fromJson(response,new TypeToken<Map<String,String>>() {}.getType());
    	
    	int code =  Integer.valueOf(map.get("code"));
    	if(code != 0){
    		throw new Exception(map.get("msg"));
    	}
		
		
		return vcode;
	}

}
